package com.woniu.consumer;

import com.rabbitmq.client.Channel;
import com.woniu.entity.Registration;
import com.woniu.mapper.RegistrationMapper;
import com.woniu.mapper.TimeSlotMapper;
import com.woniu.utils.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class UpdateRegistrationConsume {
    @Resource
    private RegistrationMapper registrationMapper;
    @Resource
    private TimeSlotMapper timeSlotMapper;
    @RabbitListener(queues = {ConstantUtil.DELAY_QUEUE})
    public void consume(String msg, Channel channel, Message message){
        log.info("取消挂号消息：{}",msg);
        try {
            Registration registration = registrationMapper.findByRsNo(msg);
            if (registration.getRsStatus() ==0) {
                registration.setRsStatus(2);
                registrationMapper.updateByPrimaryKeySelective(registration);
                timeSlotMapper.updateByPrimaryKey(timeSlotMapper.selectByPrimaryKey(registration.getTimeSlotId()));
                log.info("取消挂号成功：{}",msg);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
